(function($){
    window.Rainbow = Rainbow = {};
    Rainbow.Grid = function (option) {
    	var grid = {};
		var config = {
		     gridId:"#grid"
		    // grid option
	    	,height:'100%'
			,idField:"id"
			,toolbar:"#toolbar"
			,fitColumns:true
			,checkOnSelect:false
			,selectOnCheck:false
			,singleSelect:true
			,showFooter:false
			,pagination:true
			,pageSize:30
			,pageList:[30,50,100]
			,align:'center'
			,loadDate:true
			,multiSort:true
			,beforeLoad:null
			,onSave:null
			,onUpdate:null
			,mode:"remote"
			,rowEditEnable:false
			,paths:[""]
			,dynamicPaths:true
			,loader:function(param,success){
				if(config.loadDate){
					var conditions=[];
					if(config.queryForm){
						conditions = config.queryForm.getData();
					}
					var orders;
					var sorts;
					var order;
					if(param.order){
						orders = param.order.split(",");
						sorts = param.sort.split(",");
						order = {};
						for(var i=0;i<orders.length;i++){
							order[sorts[i]]=orders[i];
						}
					}
					
					var filterOption = {
						 "mode":"and"
		                ,"conditions":conditions
		                ,"pageNumber":param.page
		                ,"pageSize":param.rows
		                ,"order":order
					}
					if(config.beforeLoad){
						config.beforeLoad(filterOption);
					}
					var paths = config.paths;
					if(config.dynamicPaths){
						var conditions = filterOption.conditions;
						var pathMap = {};
						for(var i=0;i<conditions.length;i++){
							var propertyName = conditions[i].propertyName;
							if(propertyName.split(".").length>1){
								var path = propertyName.substring(0,propertyName.lastIndexOf("."));
								pathMap[path]=true;
							}
						}
						Object.keys(pathMap).forEach(function(key){
						     paths.push(key);
						});
					}
					
					ServiceUnit.query(config.serviceName,filterOption,paths,function (result) {
						if(result.data){
							if(config.pagination){
								var data={};
    							data["rows"] = result.data;
    							if(result.total){
    								data["total"] = result.total;
    							}
    							success(data);
							}else{
								success(result.data);
							}
						};
					});
				}else{
					success([]);
				}
				
			}
			,onSelect:function(index,row){
				if(config.rowEditEnable){
					if(grid.editIndex != null && config.singleSelect){
						grid.datagrid('endEdit',grid.editIndex);
					}
					grid.editIndex = index;
					grid.datagrid('beginEdit',grid.editIndex);
				}
				if(grid.selectRow){
   					if(index == grid.datagrid('getRowIndex',grid.selectRow)){
   						grid.datagrid('unselectRow',index);
   						grid.selectRow = null;
   					}else{
   						grid.selectRow = row;
   					}
   				}else{
   					grid.selectRow = row;
   				}
				
   				
		     }
		    ,onUnselect:function(index,row){
		    	if(config.rowEditEnable){
			    	grid.datagrid('endEdit',index);
			    	grid.editIndex = null;
		    	}
			}
		    ,onBeginEdit:function(index,row){
		    	if(config.rowEditEnable){
					var editors = grid.datagrid('getEditors',index);
					for(var i=0;i<editors.length;i++){
						$(editors[i].target).next().children('.textbox-text').bind("focus", function (e) {
							grid.editIndex = $(e.target).parents(".datagrid-row").attr("datagrid-row-index");
						})
					}
				}
		    }
		    ,onEndEdit:function(){
		    	if(config.rowEditEnable){
			    	grid.editIndex = null;
		    	}
		    }
        };
	    config = $.extend(config,option);
        
	    grid = $.extend($(config.gridId).datagrid(config),grid);
        grid.editIndex = null;
        
        grid.get = function(paths,id){
        	var row = grid.datagrid("getSelected");
        	var data;
    		if(row != null){
    			var params = [row.id];
    			if(paths){
     				params.push(paths)
     			}else{
     				params.push(config.paths)
     			}
    			ServiceUnit.execute(config.serviceName,"get",params,function (result) {
					data = result.data
				});
    		}else if(id){
    			var params = [id];
    			if(paths){
    				params.push(paths)
    			}
    			ServiceUnit.execute(config.serviceName,"get",params,function (result) {
					data = result.data
				});
    		}
    		return data;
        }
        
        grid.save = function(dialog){
        	dialog.config.form.reset();
        	if(config.onSave){
        		config.onSave();
        	}
        	dialog.dialog("open");
        	//grid.datagrid("unselectAll");
        }
        grid.update = function(dialog,form,paths,id){
        	var data; 
    		if(config.mode=="remote"){
    			data = grid.get(paths,id);
    		}else{
    			data = grid.datagrid("getSelected");
    		}	
        	if(data){
        		grid.save(dialog);
            	if(config.onUpdate){
            		config.onUpdate(data);
            	}
        		form.setData(data);
        	}
        	
        }
        grid.batch = function(method,service,actionInfo){
        	var rows = [].concat(grid.datagrid("getChecked"));
        	if(!actionInfo){
        		actionInfo = "操作"
        	}
        	if(!service){
        		service = config.serviceName
        	}
        	if(!rows.length>0){
        		$.messager.alert("提示","请选择要"+actionInfo+"的记录！","info");
        		return;
        	}
        	$.messager.confirm({
				title: '提示',
				msg: actionInfo+rows.length+'条记录？',
				fn: function(r){
					if (r){
						if(config.mode=="remote"){
							var ids = [];
							for(var i=0;i<rows.length;i++){
								ids.push(rows[i].id);
							}
			        		var params=[ids];
			        		ServiceUnit.execute(service,method,params,function(result){
								grid.datagrid('reload');
								Rainbow.Util.msgSuccessShow();
								grid.datagrid("clearChecked");
							});
			        	}else if(config.mode=="local"){
			        		for(var i=0;i<rows.length;i++){
			        			var index = grid.datagrid("getRowIndex",rows[i]);
				        		grid.datagrid("deleteRow",index);
				        		console.log(rows.length);
			        		}
			        	}
					}else{
						grid.datagrid("clearChecked");
					}
					
				}
			});
        	
        }
        grid.delete = function(){
        	grid.batch("delete",config.serviceName,"删除")
        }
        grid.query = function(dialog){
        	if(config.onQuery){
        		config.onQuery();
        	}
    		dialog.dialog("open");
        }
        grid.load = function(){
        	grid.datagrid("load");
        	grid.datagrid("unselectAll");
        }
        
        grid.clear = function(){
        	grid.loadData([]);
        }
        
        grid.loadData = function(data){
        	grid.datagrid("loadData",data);
        }
        
        grid.appendRow = function(row){
        	grid.datagrid('appendRow',$.extend({},row));
        	return grid.datagrid("getRows").length-1;
        }
        grid.acceptChanges = function(callback){
        	grid.datagrid('acceptChanges');
        	grid.datagrid("clearChecked");
        	if(callback){
        		callback();
        	}
        	grid.editIndex = null;
        }
        grid.getEditRow = function(){
        	if(config.rowEditEnable && grid.editIndex!=null){
		    	return grid.getRow(grid.editIndex);
	    	}
        }
        grid.getRow = function(index){
        	return grid.datagrid("getRows")[index];
        }
        return grid;
    }
    
    Rainbow.TreeGrid = function(option){
    	var treeGrid = {};
    	var config = {
   		     gridId:"#treeGrid"
   	    	,height:"100%"
   	    	,checkbox:true
   	    	,checkOnSelect:false
			,selectOnCheck:false
			,cascadeCheck:true
			,autoCheckParentNode:false
			,parentIdName:"parent.id"
   			,idField:"id"
   			,toolbar:"#toolbar"
   			,fitColumns:true
   			,align:"center"
   			,beforeLoad:null
   			,afterLoad:null
   			,loadDate:true
   			,paths:[""]
    		,deleteMode:"remote"
    		,dataRender:function(result){
    			if(result.data){
					var data={};
					data["rows"] = result.data;
					if(result.total){
						data["total"] = result.total;
					}
					return data;
				}
    		}
   			,loader:function(param,success){
   				if(config.loadDate){
   					var conditions=[];
   					if(config.queryForm){
   						conditions = config.queryForm.getData();
   					}
   				
   					var filterOption = {
   						 "mode":"and"
   		                ,"conditions":conditions
   		                ,"pageNumber":param.page
   		                ,"pageSize":param.rows
   		                ,"order":null
   					}
   					if(config.beforeLoad){
   						config.beforeLoad(filterOption);
   					}
   					ServiceUnit.request({
   		                "serviceName":config.serviceName
   		                ,"methodName":config.methodName
   		                ,"params":[ServiceUnit.filter(filterOption),config.paths]
   		                ,"callback":function (result) {
   		                	if(config.afterLoad){
   		                		config.afterLoad(result);
   		                	}
   							success(config.dataRender(result));	
   	   					}
   		            });
   				}else{
   					success([]);
   				}
   			}
   			,onSelect:function(row){
   				if(treeGrid.selectRow){
   					if(row.id == treeGrid.selectRow.id){
   						treeGrid.treegrid('unselect',row.id);
   						treeGrid.selectRow = null;
   					}else{
   						treeGrid.selectRow = row;
   					}
   				}else{
   					treeGrid.selectRow = row;
   				}
   			}
   			,onCheckNode:function(row,checked){
   				if(config.autoCheckParentNode){
   					var node = row;
   					while((parentId = Rainbow.Util.getObjWithJsonExp(node,config.parentIdName))!=null){
   						var parent = treeGrid.treegrid('find',parentId);
   						if(!parent.checked && checked){
   							treeGrid.treegrid('checkNode',parentId);
   						}
   						node = parent;
   					}
   					
					
					
					/*if(!row.autoCheck){
						for(var i=0;i<children.length;i++){
							if(checked){
								treeGrid.treegrid('checkNode',children[i].id);
							}else{
								treeGrid.treegrid('uncheckNode',children[i].id);
							}
						}
					}*/
					
					
					
					
   				}
   			}
   			,onBeforeCheckNode:function(row,checked){
   				if(config.autoCheckParentNode && !checked){
   					//查看子节点是否有选中
	   				var children = treeGrid.treegrid('getChildren',row.id);
   					for(var i=0;i<children.length;i++){
						if(children[i].checked){
							return false;
						}
					}
	   				
   					return true;

   				}
   			}
        };
    	
   	    config = $.extend(config,option);
   	    treeGrid = $.extend($(config.gridId).treegrid(config),treeGrid);
   	    
   	    treeGrid.selectRow = null;
   	    
   	    treeGrid.query = function(dialog){
	     	if(dialog){
	     		dialog.dialog("open");
	     	}else{
	     		treeGrid.treegrid("load");
	     		treeGrid.treegrid("unselectAll");
	     	}
   	    }
   	    
   	    treeGrid.get = function(paths,id){
	     	var row = treeGrid.treegrid("getSelected");
	     	var data;
	     	var params=[];
	     	var requestFlag = false;
	 		if(row != null){
	 			var params = [row.id];
	 			requestFlag = true;
	 		}else if(id != null){
	 			var params = [id];
	 			requestFlag = true;
	 		}
	 		if(paths){
 				params.push(paths)
 			}else{
 				params.push(config.paths)
 			}
	 		if(requestFlag){
	 			ServiceUnit.execute(config.serviceName,"get",params,function (result) {
					data = result.data
				});
	 		}
 			
 			return data;
   	    }
   	    treeGrid.save = function(dialog){
	     	dialog.config.form.reset();
	     	if(config.onSave){
	     		config.onSave();
	     	}
	     	dialog.dialog("open");
	     	//treeGrid.treegrid("unselectAll");
   	    }
   	    treeGrid.update = function(dialog,form,paths,id){
	     	var data = grid.get(paths,id);
	     	if(data){
		     	treeGrid.save(dialog);
		     	if(config.onUpdate){
		     		config.onUpdate(data);
		     	}
		     	form.setData(data);
	     	}
   	    }
   	    treeGrid.delete = function(){
	     	var rows = [].concat(treeGrid.treegrid("getCheckedNodes"));
	     	if(!rows.length>0){
        		$.messager.alert("提示","请选择要删除的记录！","info");
        		return;
        	}
	     	$.messager.confirm({
					title: '提示',
					msg: '删除'+rows.length+'条记录？',
					fn: function(r){
						if (r){
							if(config.deleteMode=="remote"){
								var ids = [];
								for(var i=0;i<rows.length;i++){
									ids.push(rows[i].id);
								}
				        		var params=[ids];
				        		ServiceUnit.execute(config.serviceName,"delete",params,function(result){
				        			Rainbow.Util.msgSuccessShow();
									for(var i=rows.length;i>0;i--){
										treeGrid.treegrid("remove",rows[i-1].id);
									}
								});
				        	}else if(config.deleteMode=="local"){
				        		
				        	}
						}else{
							for(var i=0;i<rows.length;i++){
								treeGrid.treegrid("uncheckNode",rows[i].id);
							}
							
						}
						
					}
				});
   	    }
   	    
   	    return treeGrid;
    }
    
    Rainbow.Tree = function(option){
    	var tree = {};
    	var config = {
			 treeId:"#tree"
   	    	,checkbox:true
   	    	,cascadeCheck:true
   	    	,lines:true
   	    	,dnd:true
   	    	,paths:[""]
			,deleteMode:"remote"
			,dialog:null
			,onSelectHandle:null
			,dialogConfig:{
				 callback:function(result){
					 var data = result.data;
					 data.text=data.name;
					 var parent = {};
					 if(data.parent.id){
						 parent = tree.tree('find',data.parent.id);
					 }
					 var node = tree.tree('find',data.id);
					 if(!node){
						 	tree.tree("append",{
								parent: parent.target
							   ,data:data
							});
					 }else{
						 tree.tree('update',{
							 target: node.target
							,text: data.text
						});
					 }
				 }
			     ,dataHandle:function(data){
			    	 if(!data.id){
			    		 var row = tree.tree("getSelected");
				    	 if(row){
				    		 data.parent = {id:row.id};
				    	 }
			    	 }
			     }
			}
   	    	,dataRender:function(result){
   	    		if(result.data){
   	    			Rainbow.Util.iterateTree(result.data,"children",function(node){
   	    				node.text = node.name;
   	    			})
   	    		}
   	    		return result.data;
   	    	}
   	    	,loader:function(param,success,error){
   					if(config.beforeLoad){
   						config.beforeLoad();
   					}
   					ServiceUnit.request({
   		                 "serviceName":config.serviceName
   		                ,"methodName":config.methodName
   		                ,"params":[null,config.paths]
   		                ,"callback":function (result) {
   		                	if(config.afterLoad){
   		                		config.afterLoad(result);
   		                	}
   							success(config.dataRender(result));	
   	   					}
   		            });
   	    	}
	   	    ,onSelect:function(row){
	   	    	if(tree.selectRow && row.id == tree.selectRow.id){
	   	    		tree.unselect();
						tree.selectRow = null;
	   	    	}else{
	   	    		tree.selectRow = row;
	   	    		if(config.onSelectHandle){
		   	    		config.onSelectHandle(row);
			   	    }
	   	    	}
   			}
	   	    ,onDrop:function(target,source,point){
	   	    	if(point == "append"){
	   	    		var targetNode = tree.tree("getNode",target);
	   	    		source.parent = {id:targetNode.id}
	   	    	}else{
	   	    		delete source.parent;
	   	    	}
	   	    	config.dialog.config.request(source);
	   	    }
    	}
    	config = $.extend(config,option);
    	tree = $.extend($(config.treeId).tree(config),tree);
    	tree.get = function(paths,id){
	     	var row = tree.tree("getSelected");
	     	var data;
	     	var params=[];
	     	var requestFlag = false;
	 		if(row != null){
	 			var params = [row.id];
	 			requestFlag = true;
	 		}else if(id != null){
	 			var params = [id];
	 			requestFlag = true;
	 		}
	 		if(paths){
 				params.push(paths)
 			}else{
 				params.push(config.paths)
 			}
	 		if(requestFlag){
	 			ServiceUnit.execute(config.serviceName,"get",params,function (result) {
					data = result.data
				});
	 		}
 			return data;
   	    }
    	tree.save = function(dialog){
	     	dialog.config.form.reset();
	     	$.extend(dialog.config,config.dialogConfig);
	     	if(config.onSave){
	     		config.onSave();
	     	}
	     	dialog.dialog("open");
   	    }
    	tree.update = function(dialog,form,paths,id){
	     	var data = tree.get(id,paths);
	     	if(data){
		     	tree.save(dialog);
		     	if(config.onUpdate){
		     		config.onUpdate(data);
		     	}
		     	form.setData(data);
	     	}
   	    }
    	tree.delete = function(){
	     	var rows = [].concat(tree.tree("getChecked"));
	     	$.messager.confirm({
					title: '提示',
					msg: '删除'+rows.length+'条记录？',
					fn: function(r){
						if (r){
							if(config.deleteMode=="remote"){
								var ids = [];
								for(var i=0;i<rows.length;i++){
									ids.push(rows[i].id);
								}
				        		var params=[ids];
				        		ServiceUnit.execute(config.serviceName,"delete",params,function(result){
				        			Rainbow.Util.msgSuccessShow();
									for(var i=rows.length;i>0;i--){
										tree.tree("remove",rows[i-1].target);
									}
								});
				        	}else if(config.deleteMode=="local"){
				        		
				        	}
						}else{
							for(var i=0;i<rows.length;i++){
								tree.tree("uncheck",rows[i].id);
							}
							
						}
						
					}
				});
   	    }
    	tree.unselect = function(){
    		if(config.onUnSelectHandle){
    			config.onUnSelectHandle();
    		}
    		tree.find("div.tree-node-selected").removeClass("tree-node-selected");
    	}
    	return tree;
    }
    
    
    Rainbow.Form = function(option){
    	var config = {
			 //formId:"#queryForm"
			inputArray:[]
    		/*
    		 input;{
    		 	 name:"name"
    		 	,lable:"名称",
    		 	,type:"textbox"
    		 	,validate:{required: true,validType: 'email'}
    		 	,condition
        	 }
        	*/
    		,colNum:-1
    		,lable:false
    		,lableWidth:false
    		,queryForm:false
    	}
    	
    	
    	config = $.extend(config,option);
    	var form = $(config.formId);
    	form.config = config;
    	var inputArray = form.config.inputArray
    	var inputObjMap = {};
    	var inputLableMap = {};
    	var num=0;
    	form.addInput = function(inputs,initFlag){
    		if(!initFlag){
    			inputArray = inputArray.concat(inputs);
    		}
    		for(var i=0;i<inputs.length;i++){
        		var lable = inputs[i].lable;
        		var type = inputs[i].type;
        		var inputOption = inputs[i].option
        		var style = inputs[i].style
        		if(!type){
        			inputs[i].type=type = "textbox";
        		}
        		var box = $("<div></div>");
        		box.css({"float":"left","margin":"10px"});
        		var input = $("<input></input>");
        		if(style){
        			input.css(style)
        		}
        		inputs[i].input = input;
        		if(form.config.lable && inputs[i].lable){
        			lable_el = $("<span>"+lable+"：</span>");
        			var lableWidth = null
        			if(config.lableWidth){
        				lableWidth = config.lableWidth;
        			}
        			if(inputs[i].lableWidth){
        				lableWidth = inputs[i].lableWidth;
        			}
        			if(lableWidth){
        				lable_el.css({"display":"inline-block","width":lableWidth});
        			}
        			box.append(lable_el);
        			if(inputs[i].id){
        				inputLableMap[inputs[i].id] = lable_el;
            		}else{
            			inputLableMap[inputs[i].name] = lable_el;
            		}
        		}
        		
    			if(type!="hidden"){
    				num++;
    				box.append(input);
    	    		form.append(box);
    	    		if((form.config.colNum>0 && num%form.config.colNum == 0) || inputs[i].newline){
    	    			form.append("<div style='clear:both;'></div>");
    	    		}
    			}else{
    				form.append(input);
    			}
        		
        		var inputObj = null;
        		var inputConfig = null;
        		if(type=="textbox"){
        			inputConfig = $.extend({prompt:lable},inputOption);
        			inputObj = input.textbox(inputConfig);
        		}else if(type=="passwordbox"){
        			inputConfig = $.extend({prompt:lable},inputOption);
        			inputObj = input.passwordbox(inputConfig);
        		}else if(type=="numberbox"){
        			inputConfig = $.extend({prompt:lable,min:0,precision:2},inputOption)
        			inputObj = input.numberbox(inputConfig);
        		}else if(type=="datebox"){
        			inputConfig = $.extend({prompt:lable},inputOption);
        			inputObj = input.datebox(inputConfig);
        		}else if(type=="datetimebox"){
        			inputConfig = $.extend({prompt:lable},inputOption);
        			inputObj = input.datetimebox(inputConfig);
        		}else if(type=="combobox"){
        			inputConfig = $.extend(inputOption,{prompt:lable});
        			inputConfig = Rainbow.inputOption.combobox(inputOption);
        			inputObj = input.combobox(inputConfig);
        		}else if(type=="combogrid"){
        			inputConfig = $.extend({prompt:lable},Rainbow.inputOption.combogrid(inputOption))
        			inputObj= input.combogrid(inputConfig);
        		}else if(type=="combotree"){
        			inputConfig = $.extend({prompt:lable},Rainbow.inputOption.combotree(inputOption))
        			inputObj= input.combotree(inputConfig);
        		}else if(type=="hidden"){
        			inputObj = input.attr("type","hidden");
        		}
        		inputObj.config = inputConfig;
        		if(inputs[i].id){
        			inputObjMap[inputs[i].id] = inputObj;
        		}else{
        			inputObjMap[inputs[i].name] = inputObj;
        		}
        	}
    	}
    	
    	form.addInput(inputArray,true);

    	
    	form.getData = function(){
    		var data;
    		if(config.queryForm){
    			data = [];
    		}else{
    			data = {};
    		}
    		
    		for(var i=0;i<inputArray.length;i++){
    			var value;
    			if(inputArray[i].type=="textbox"){
    				value = inputArray[i].input.textbox('getValue');
    			}else if(inputArray[i].type=="passwordbox"){
    				value = inputArray[i].input.passwordbox('getValue');
    			}else if(inputArray[i].type=="numberbox"){
    				value = inputArray[i].input.numberbox('getValue');
    			}else if(inputArray[i].type=="datebox"){
    				value = inputArray[i].input.datebox('getValue');
    			}else if(inputArray[i].type=="datetimebox"){
    				value = inputArray[i].input.datetimebox('getValue');
    			}else if(inputArray[i].type=="combobox"){
    				if(!inputArray[i].input.config.multiple){
    					value = inputArray[i].input.combobox('getValue');
    				}else{
    					value = inputArray[i].input.combobox('getValues');
    				}
    			}else if(inputArray[i].type=="combogrid"){
    				if(!inputArray[i].input.config.multiple){
    					value = inputArray[i].input.combogrid('getValue');
    				}else{
    					value = inputArray[i].input.combogrid('getValues');
    				}
    			}else if(inputArray[i].type=="combotree"){
    				if(!inputArray[i].input.config.multiple){
    					value = inputArray[i].input.combotree('getValue');
    				}else{
    					value = inputArray[i].input.combotree('getValues');
    				}
    			}else if(inputArray[i].type=="hidden"){
    				if(inputArray[i].input.val()!=""){
    					value = inputArray[i].input.val();
    				}else{
    					value = null;
    				}
    			}
    			if(value=="" && inputArray[i].type!="textbox"){
    				value = null;
    			}
    			if(config.queryForm && value && value!="" ){
    				if(Array.isArray(value)){
    					data.push({"propertyName":inputArray[i].name,"operate":inputArray[i].condition,value:value})
    				}else{
    					data.push({"propertyName":inputArray[i].name,"operate":inputArray[i].condition,value:[value]})
    				}
    				
    			}else{
    				var names = inputArray[i].name.split(".");
        			if(names.length==1){
    					data[inputArray[i].name] = value;
    				}else{
    					var tempObj;
    					for(var j=0;j<names.length;j++){
    						if(j==names.length-1){
    							tempObj[names[j]] = value;
    						}else{
    							if(!data[names[j]]){
        							data[names[j]]={}
        						}
        						tempObj = data[names[j]];
    						}
    					}
    				}
    			}
    		}
    		return data;
    	}
    	
    	form.setData = function(data){
    		if($.isPlainObject(data)){
    			for(var i=0;i<inputArray.length;i++){
        			if(validateNestedExp(data,inputArray[i].name)){
        				var value = eval('data.'+inputArray[i].name);
        				if(value){
        					if(inputArray[i].type=="textbox"){
                				inputArray[i].input.textbox('setValue',value);
                			}else if(inputArray[i].type=="numberbox"){
                				inputArray[i].input.numberbox('setValue',value);
                			}else if(inputArray[i].type=="datebox"){
                				inputArray[i].input.datebox('setValue',value);
                			}else if(inputArray[i].type=="datetimebox"){
                				inputArray[i].input.datetimebox('setValue',value);
                			}else if(inputArray[i].type=="combobox"){
                				if(!inputArray[i].input.config.multiple){
                					inputArray[i].input.combobox('setValue',value);
                				}else{
                					inputArray[i].input.combobox('setValues',value);
                				}
                			}else if(inputArray[i].type=="combogrid"){
                				if(!inputArray[i].input.config.multiple){
                					inputArray[i].input.combogrid('setValue',value);
                				}else{
                					inputArray[i].input.combogrid('setValues',value);
                				}
                			}else if(inputArray[i].type=="combotree"){
                				if(!inputArray[i].input.config.multiple){
                					inputArray[i].input.combotree('setValue',value);
                				}else{
                					inputArray[i].input.combotree('setValues',value);
                				}
                			}else if(inputArray[i].type=="hidden"){
                				inputArray[i].input.val(value);
                			}
        				}
        				
        			}
    			}
    		
    			
    		}
    		
    		function validateNestedExp(data,exp){
    			if(exp){
    				exps = exp.split(".");
    				temp = null;
    				for(j=0;j<exps.length;j++){
    					if(temp == null){
    						temp = exps[j];
    					}else{
    						temp=temp+"."+exps[j]
    					}
    					if(typeof(eval('data.'+temp))=="undefined"){
    						return false;
    					}
    				}
    				return true;
    			}else{
    				return false;
    			}
    		}
    	}
    	
    	form.reset = function(){
    		for(var i=0;i<inputArray.length;i++){
    			if(inputArray[i].type=="textbox"){
    				inputArray[i].input.textbox('reset');
    			}else if(inputArray[i].type=="passwordbox"){
    				inputArray[i].input.passwordbox('reset');
    			}else if(inputArray[i].type=="numberbox"){
    				inputArray[i].input.numberbox('reset');
    			}else if(inputArray[i].type=="datebox"){
    				inputArray[i].input.datebox('reset');
    			}else if(inputArray[i].type=="datetimebox"){
    				inputArray[i].input.datetimebox('reset');
    			}else if(inputArray[i].type=="combobox"){
    				inputArray[i].input.combobox('reset');
    			}else if(inputArray[i].type=="combogrid"){
    				inputArray[i].input.combogrid('reset');
    			}else if(inputArray[i].type=="combotree"){
    				inputArray[i].input.combotree('reset');
    			}else if(inputArray[i].type=="hidden"){
    				inputArray[i].input.val("");
    			}
    		}
    	}
    	
    	form.getInputObj = function(id){
    		return inputObjMap[id];
    	}
    	
    	form.getInputLable = function(id){
    		return inputLableMap[id];
    	}
    	
    	return form
    };
    
    Rainbow.Dialog = function(option){
    	var dialog;
    	var form = option.form;
    	var config ={
    		//serviceName
    		//methodName	
    		//form:	
			 width: '100%'
		 	,height: '100%'
			,closed: true
			,modal: true
		    ,closable:false
		    ,onConfirm:null
		    ,onBeforeValidate:null
		    ,request: function(data){
		    	ServiceUnit.execute(config.serviceName,config.methodName,[data],function (result) {
					Rainbow.Util.msgSuccessShow();
					if(config.callback){
						config.callback(result);
					}
					
				});
		    }
		    ,buttons:[{
				text:'确认',
				iconCls:'icon-ok',
				handler:function(){
					if(config.onBeforeValidate){
						config.onBeforeValidate();
					}
					var isValid = $(config.dialogId).form('validate');
					if(isValid){
						var confirm = true;
						if(config.onConfirm){
							confirm = config.onConfirm();
						}
						var data = form.getData();
						if(dialog.config.dataHandle){
							dialog.config.dataHandle(data);
						}
						if(confirm){
							config.request(data);
						}
						dialog.dialog('close');
						
					}
				}
			},{
				text:'取消',
				iconCls:'icon-cancel',
				handler:function(){
					dialog.dialog('close');
				}
			}]
    	};
    	
    	config = $.extend(config,option);
    	dialog = $(config.dialogId).dialog(config);
    	dialog.config = config;
    	
    	return dialog;
    }
    
    Rainbow.Window = function(option){
    	var window;
    	
    	var config ={
			 width:'100%'
		    ,height:'100%'
		    ,modal:true
		    ,collapsible:false
		    ,minimizable:false
		    ,maximizable:false
		    ,closed:true
		    ,iframe:false
    	};
    	config = $.extend(config,option);
    	
    	if(config.iframe){
    		var iframeId = config.windowId.substring(1)+"_iframe";
    		var content = '<iframe id='+iframeId+' scrolling="auto" frameborder="0" style="width:100%;height:100%;"></iframe>';
    		config.content = content;
    		config.iframeId = iframeId;
    	}
    	window = $(config.windowId).window(config);
    	window.config = config;
    	window.open = function(url){
    		window.window('open');
    		if(config.iframe){
    			$('#'+config.iframeId).attr('src',url);
    		}
    	}
    	return window;
    }
    
    Rainbow.inputOption={
    	combotreegrid : function(option){
    		var config = {
    				idField:'id'
    			   ,textField:'name'
    			   ,treeField:null
    			   ,fitColumns:true
    	   		   ,align:"center"
    	   		   ,loader:null
    		}
    		config = $.extend(config,option);
    		return config;
    	},
    	combotree : function(option){
    		var config = {
    			 textField:'name'
    			,editable:true
    			,onChange(newValue, oldValue){
    				
    			}
    		}
    		config = $.extend(config,option);
    		return config;
    	},
    	combogrid : function(option){
    		var config = {
    	             idField:'id'
    	            ,textField:'name'
    	            ,mode:'remote'
    	            ,panelWidth:550
    	            ,fitColumns:true
    	            ,autoRowHeight:true
    	            ,paramName:""
	            	,pagination:false
	    			,pageSize:10
	    			,pageList:[10,30,100]
    	            ,beforeLoad:null
    	            ,conditions:[]
    				,beforeload:null
    				,paths:[""]
    	            ,loader:function(param,success){
    	            	var conditions=[];
    	            	if(param.q){
    	            		conditions.push({"propertyName":config.paramName,"operate":"like","value":[param.q]});
    	            	}
    	            	conditions = conditions.concat(config.conditions);
    	            	
    	            	var isload = true;
    	            	if(config.beforeload){
    	            		isload = config.beforeload(conditions);
    	            	}
    	            	
    	            	if(isload){
    	            		var filterOption = {
    	    						 "mode":"and"
    	    		                ,"conditions":conditions
    	    		                ,"pageNumber":param.page
    	    		                ,"pageSize":param.rows
    	    		                ,"order":null
    	    					}
    	    					if(config.beforeLoad){
    	    						config.beforeLoad(filterOption);
    	    					}
    	    					ServiceUnit.query(config.serviceName,filterOption,config.paths,function (result) {
    	    						if(result.data){
    	    							if(config.pagination){
    	    								var data={};
    	        							data["rows"] = result.data;
    	        							if(result.total){
    	        								data["total"] = result.total;
    	        							}
    	        							success(data);
    	    							}else{
    	    								success(result.data);
    	    							}
    	    							
    	    						};
    	    					});
    	            	}else{
    	            		success({rows:[],total:0});
    	            	}
    					
    	            }
    	    	};
    		config = $.extend(config,option);
    		return config
    	},
    	combobox : function(option){
    		var config = {
				 valueField:'id'
				,textField:'name'
				,loader:function(param,success,error){
					if(option && option.code){
						success(CodeCache.getCodeList(option.code));
					}
				}
        	}
    		config = $.extend(config,option);
    		return config
    	},
    	numberbox : function(option){
    		var config = {
    			precision:2
    		}
    		config = $.extend(config,option);
    		return config
    	}
    }
    
    Rainbow.Util = {	
		format:{
			money:function(num,precision){
				if("undefined" == typeof num){
					num=0;
				}
				if("undefined" == typeof precision){
					precision=2;
				}
	    		return (parseFloat(num).toFixed(precision) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
	    	}
    	   ,date(dataTime){
    		   if(dataTime){
    			   var fullDate = dataTime.split(" ");  
    			   return fullDate[0]; 
    		   }
    		}
		},
	    getUrlParam : function(paramName){
			var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
	        var r = window.location.search.substr(1).match(reg);
	        if (r != null) return r[2]; return null;
		},
		initButton : function(toolbarId,resourceCode){
			var menuId = decodeURIComponent(Rainbow.Util.getUrlParam("menuId"));
			var condition = {propertyName:"parent.id",operate:"eq",value:[menuId]};
			if(resourceCode){
				condition.propertyName = "parent.code";
				condition.value = [resourceCode];
			}
			
			var filterOption = {
					 "mode":"and"
	                ,"conditions":[condition,{propertyName:"type",operate:"eq",value:["resource_button"]}]
	                ,"order":{"sort":1}
			}
			
			var option = {
	                "serviceName":"AuthorityService"
	               ,"methodName":"getAcountResource"
	               ,"params":[ServiceUnit.filter(filterOption),null,null,null,null,["parent"]]
	               ,"async":false
	               ,"callback":function(result){
		            	var buttons = result.data;
		       			if(buttons){
		       				for(var i=0;i<buttons.length;i++){
		       					button = buttons[i];
		       					$.extend(button,JSON.parse(buttons[i].config));
		       					button_html = "<a href='#' id="+button.id+" class='easyui-linkbutton' iconCls='"+button.iconCls+"' onclick='"+button.onclick+"' plain='true'>"+button.name+"</a>";
		       					$(toolbarId).append(button_html);
		       				}
		       			}
	               }
	           };
	  		ServiceUnit.request(option);
			
		},
		guid:function(){
			 function S4() {
				 return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
			 }
			 return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
		},
		msgSuccessShow:function(){
			Rainbow.Util.msg('操作成功！');
		},
		msg:function(text){
			$.messager.show({
				title:'提示信息',
				msg:text,
				iconCls:'icon-tip',
				timeout:1000,
				showType:'fade',
				closable:false
			});
		},
		getObjWithJsonExp:function(data,exp){
			var obj = data;
			if(obj){
				var exps = exp.split(".");
				for(var i=0;i<exps.length;i++){
					obj = obj[exps[i]];
					if(obj == null){
						break;
					}
				}
			}
			return obj;
		},
		iterateTree:function(data,childName,callback){
 			var stack = [].concat(data);
 			while (stack.length > 0) {
    		   node = stack.pop();
    		   callback(node);
			   if(node[childName]){
				   for(var i=0;i<node[childName].length;i++){
					   stack.push(node[childName][i]);
				   }
			   }
    		}
		},
		getDateStr:function (date){
			var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
			var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0"
			+ (date.getMonth() + 1);
			var hor = date.getHours();
			var min = date.getMinutes();
			var sec = date.getSeconds();
			return date.getFullYear() + '-' + month + '-' + day+" 00:00:00";
		},
		getTimeStr:function(date){
			var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
			var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0"
			+ (date.getMonth() + 1);
			var hor = date.getHours();
			var min = date.getMinutes();
			var sec = date.getSeconds();
			return date.getFullYear() + '-' + month + '-' + day+" "+hor+":"+min+":"+sec;
		}
    }
    
    Rainbow.DataDictionary = {
    	getChild : function(code,callback){
    		var filterOption = {
				 "mode":"and"
                ,"conditions":[{"propertyName":"code","operate":"eq",value:[code]}]
                ,"order":{"sort":1}
			}
    		ServiceUnit.execute("DataDictionaryService","queryChild",[ServiceUnit.filter(filterOption)],callback);
    	},
    	getAllChild : function(code,callback){
    		
    	},
    	get(code,callback){
    		var filterOption = {
   				 "mode":"and"
                   ,"conditions":[{"propertyName":"code","operate":"eq",value:[code]}]
    			   ,"order":{"sort":1}
   			}
       		ServiceUnit.execute("DataDictionaryService","query",[ServiceUnit.filter(filterOption)],callback);
    	}
    }

})(jQuery);
var CodeCache = {
	getCodeList:function(category){
		var list = CodeCache[category+"_list"];
		if(!list){
			Rainbow.DataDictionary.getChild(category,function(result){
				CodeCache[category+"_list"] = result.data;
				list = result.data;
				for(var i=0;i<list.length;i++){
					if(list[i].type){
						if(list[i].type == "number"){
							list[i].value = Number(list[i].value);
						}else if(list[i].type == "boolean"){
							list[i].value = Boolean(list[i].value);
						}else if(list[i].type == "josn"){
							
						}
					}
				}
			});
		}
		return list;
	}
	,getCodeMap:function(category){
		var map = CodeCache[category+"_map"];
		if(!map){
			var list = CodeCache.getCodeList(category);
			if(list && list.length>0){
				map = {};
				for(var i=0;i<list.length;i++){
					map[list[i].code]=list[i];
				}
			}
		}
		return map;
	}
	,getCodeData(code){
		var codeData = CodeCache[code];
		if(!codeData){
			Rainbow.DataDictionary.get(code,function(result){
				if(result.data && result.data.length>0){
					codeData = result.data[0];
					CodeCache[code] = codeData;
				}
			});
		}
		return codeData;
	}
	,getNameByCode:function(category,code){
		var map = CodeCache.getCodeMap(category);
		if(map && map[code]){
			return map[code].name;
		}
		return null;
	}
	,getNameByValue:function(category,value){
		var list = CodeCache.getCodeList(category);
		if(list){
			for(var i=0;i<list.length;i++){
				if(list[i].value == value){
					return list[i].name;
				}
			}
		}
		return null;
	}
}